package com.chuantou.yuba.ui.widget;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.TreeMap;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chuantou.yuba.R;
import com.chuantou.yuba.api.to.CityListTO;
import com.chuantou.yuba.api.to.CityTO;
import com.chuantou.yuba.ui.widget.LetterBar.OnLetterChangedListener;
import com.chuantou.yuba.util.ViewHolder;
import com.google.gson.Gson;

public class CityPopupWindow extends PopupWindow {
	private Activity mActivity;
	private ExpandableListView mListView;
	private LetterBar mLetterBar;
	private CityAdapter mAdapter;
	private List<String> mSpells = new ArrayList<String>();
	private TreeMap<String, List<CityTO>> mCities = new TreeMap<String, List<CityTO>>();
	private LayoutInflater mInflater;
	private OnCityClickListener mListener;

	public CityPopupWindow(Activity activity) {
		mActivity = activity;
		mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = mInflater.inflate(R.layout.city_popup, null);
		mListView = (ExpandableListView) view.findViewById(android.R.id.list);
		mLetterBar = (LetterBar) view.findViewById(R.id.letter_bar);
		mLetterBar.setOnLetterChangedListener(new OnLetterChangedListener() {

			@Override
			public void onLetterChanged(String letter) {
				mListView.setSelectedGroup(getCharPostion(letter));
			}
		});
		Drawable divider = activity.getResources().getDrawable(R.drawable.transparent);
		mListView.setSelector(R.drawable.list_selector);
		mListView.setChildDivider(divider);
		mListView.setDivider(divider);
		mListView.setDividerHeight(0);
		mListView.setGroupIndicator(divider);
		CityListTO list = parseLocalCity(activity);
		if (list != null) {
			List<CityTO> provinces = list.getCities();
			for (CityTO province : provinces) {
				List<CityTO> cities = province.getCities();
				if (cities != null) {
					for (CityTO city : cities) {
						String firstSpell = city.getFirstSpell();
						if (!mSpells.contains(firstSpell)) {
							mSpells.add(firstSpell);
						}
						List<CityTO> cityList = mCities.get(firstSpell);
						if (cityList == null) {
							cityList = new ArrayList<CityTO>();
							mCities.put(firstSpell, cityList);
						}
						cityList.add(city);
					}
				}
			}
		}
		Collections.sort(mSpells, mSpellCompare);
		mAdapter = new CityAdapter();
		mListView.setAdapter(mAdapter);
		mListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
				if (mListener != null) {
					String spell = mSpells.get(groupPosition);
					List<CityTO> cities = mCities.get(spell);
					CityTO city = cities.get(childPosition);
					mListener.onCityClick(city);
				}
				dismiss();
				return true;
			}
		});
		setContentView(view);
		setHeight(FrameLayout.LayoutParams.MATCH_PARENT);
		setWidth(FrameLayout.LayoutParams.MATCH_PARENT);
		setFocusable(true);
		setAnimationStyle(R.style.popup_style);
		ColorDrawable drawable = new ColorDrawable(activity.getResources().getColor(R.color.translucence));
		setBackgroundDrawable(drawable);
		for (int i = 0; i < mCities.size(); i++) {
			mListView.expandGroup(i);
		}
	}

	public int getCharPostion(String letter) {
		int position = -1;
		if (mSpells != null && !mSpells.isEmpty()) {
			for (int i = 0; i < mSpells.size(); i++) {
				String spell = mSpells.get(i);
				if (letter.equals(spell)) {
					position = i;
					break;
				}
			}
		}
		return position;
	}

	public void setOnCityClickListener(OnCityClickListener l) {
		mListener = l;
	}

	private Comparator<String> mSpellCompare = new Comparator<String>() {

		@Override
		public int compare(String lhs, String rhs) {
			char one = lhs.charAt(0);
			char another = rhs.charAt(0);
			if (one == another) {
				return 0;
			}
			return one > another ? 1 : -1;
		}
	};

	private CityListTO parseLocalCity(Context context) {
		try {
			InputStream in = context.getAssets().open("cities");
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			String str = reader.readLine();
			Gson gson = new Gson();
			return gson.fromJson(str, CityListTO.class);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	private class CityAdapter extends BaseExpandableListAdapter {

		@Override
		public int getGroupCount() {
			return mCities == null ? 0 : mCities.size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			String spell = mSpells.get(groupPosition);
			List<CityTO> cities = mCities.get(spell);
			return cities == null ? 0 : cities.size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			return mCities.get(groupPosition);
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			String spell = mSpells.get(groupPosition);
			List<CityTO> cities = mCities.get(spell);
			return cities == null ? null : cities.get(childPosition);
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.menu_category_header, null);
			}
			String spell = mSpells.get(groupPosition);
			TextView titleTxt = ViewHolder.get(convertView, R.id.text);
			titleTxt.setText(spell);
			convertView.setClickable(false);
			return convertView;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.menu_item, null);
				convertView.setBackgroundResource(R.drawable.list_selector);
			}
			TextView view = ViewHolder.get(convertView, R.id.text);
			view.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
			String spell = mSpells.get(groupPosition);
			List<CityTO> cities = mCities.get(spell);
			CityTO city = cities.get(childPosition);
			view.setText(city.getName());
			return convertView;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}

	}

	public static interface OnCityClickListener {
		void onCityClick(CityTO city);
	}
}
